package cn.gotom.pinggu.web;

import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;

import cn.gotom.core.web.GuiceListener;
import cn.gotom.pinggu.service.SyncUserService;

import com.google.inject.ProvisionException;

/***
 * 
 * 同步服务
 * 
 * @author peixere@qq.com
 * 
 */
public final class StartListener extends GuiceListener
{
	private final Logger log = Logger.getLogger(getClass());

	private final Timer timer = new Timer("用户数据定时同步");

	class SyncTask extends java.util.TimerTask
	{

		@Override
		public void run()
		{
			if (new Date().getHours() >= 22)
			{
				log.info("开始执行数据同步" + new Date());
				syncTaskCallback();
				log.info("执行数据同步结束" + new Date());
			}
		}

	}

	private void syncTaskCallback()
	{
		try
		{

			if (injector != null)
			{
				SyncUserService syncUserService = injector.getInstance(SyncUserService.class);
				syncUserService.syncUser();
			}
		}
		catch (ProvisionException ex)
		{
			log.info("persistService.starting...   " + ex.getMessage());
		}
		catch (Throwable ex)
		{
			log.error("执行数据同步异常", ex);
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0)
	{
		super.contextInitialized(arg0);
		/**
		 * 在1分钟后执行此任务,每次间隔60分钟,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
		 */
		timer.schedule(new SyncTask(), 60 * 60000, 12 * 60 * 60000);
		// timer.schedule(new SyncTask(), 1000, 1000);
		log.info("Timer.schedule  " + injector);
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0)
	{
		super.contextDestroyed(arg0);
		log.info("Timer.cancel");
		timer.cancel();

	}

}
